#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import datetime
from os import path
import paramiko

NOW_DATE = datetime.datetime.now().strftime("%Y%m%d")

UPLOAD_FILE_PREFIX = 'pmcid_todo_'
REMOTE_PATH = '/data/pmc_meta'

SSH_HOST = "fr.snowage.net"
SSH_USER = "dataadmin"
SSH_PASSWORD = "data123"


def GetConfig():
    import ConfigParser

    if path.exists("../config.ini"):
        print("Parsing config file...")
        global UPLOAD_FILE_PREFIX
        global REMOTE_PATH

        global SSH_HOST
        global SSH_USER
        global SSH_PASSWORD
        config = ConfigParser.ConfigParser()
        config.read("../config.ini")
        if config.has_option("file", "upload_file_prefix"):
            UPLOAD_FILE_PREFIX = config.get("file", "upload_file_prefix")
        if config.has_option("file", "remote_path"):
            REMOTE_PATH = config.get("file", "remote_path")
        if config.has_option("ssh", "ssh_host"):
            SSH_HOST = config.get("ssh", "ssh_host")
        if config.has_option("ssh", "ssh_user"):
            SSH_USER = config.get("ssh", "ssh_user")
        if config.has_option("ssh", "ssh_password"):
            SSH_PASSWORD = config.get("ssh", "ssh_password")


def UploadFile(sftp, filename):
    sftp.put(filename, REMOTE_PATH + "/" + filename)


def VerifyRemote(sftp, filename):
    result = False
    filelist = sftp.listdir(path=REMOTE_PATH)
    for item in filelist:
        if item == filename:
            result = True
            break
    return result


if __name__ == "__main__":
    print("Start uploading todo list file.")
    GetConfig()

    filename = UPLOAD_FILE_PREFIX + NOW_DATE + '.txt'
    if not path.exists(filename):
        print("Todo list file " + filename + " does not exist.")
    elif path.getsize(filename) == 0:
        print("Blank file " + filename + ", please check.")
    else:
        print("Connecting SFTP server...")
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(SSH_HOST, port=22, username=SSH_USER, password=SSH_PASSWORD)
        sftp = ssh.open_sftp()
        print("Start uploading...")
        while not VerifyRemote(sftp, filename):
            print "Not verified or no file. Try again."
            UploadFile(sftp, filename)
        print("Todo list file" + filename + " has been uploaded.")
        sftp.close()
        ssh.close()
